from tornado.web import StaticFileHandler, Application
from tornado.ioloop import IOLoop
from game.ws import GameHandler

from game.player import Player
from game.room import Room
from game.games.blackwhite import BlackWhiteChess


def clean_up(clean=True):
    if clean:
        Player.clean()
        Room.clean()
    IOLoop.current().call_later(5 * 60, clean_up)


def start_server(port=8000, debug=True):
    Room.register(BlackWhiteChess)
    clean_up(False)
    application = Application([
        (r"/game", GameHandler),
        (r"/(.*)", StaticFileHandler, {"path": "static", "default_filename": "index.html"}),
    ], debug=debug)
    application.listen(port)
    IOLoop.current().start()


if __name__ == "__main__":
    debug = True
    port = 8000
    import sys
    import logging
    logger = logging.getLogger('game')
    logger.setLevel(logging.DEBUG)

    if len(sys.argv) > 1:
        if sys.argv[1] == 'prod':
            debug = False

    if debug:
        handler = logging.StreamHandler()
    else:
        handler = logging.handlers.RotatingFileHandler(filename='game.log', maxBytes=1024 * 1024 * 10, backupCount=5)
        handler.setFormatter(logging.Formatter('%(asctime)s %(name)s %(levelname)s %(message)s'))
    logger.addHandler(handler)

    start_server(port, debug)

